<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">





  <link rel="alternate" href="/atom.xml" title="renhao" type="application/atom+xml">






<meta name="description" content="本文总结下前端性能及我们在开发过程中应该考虑到优化性能的部分">
<meta property="og:type" content="article">
<meta property="og:title" content="前端性能及其优化">
<meta property="og:url" content="https://huangrenhao.gitee.io/2020/09/07/browser-performance-optimization/index.html">
<meta property="og:site_name" content="renhao">
<meta property="og:description" content="本文总结下前端性能及我们在开发过程中应该考虑到优化性能的部分">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://huangrenhao.gitee.io/2020/09/07/browser-performance-optimization/performance-timing.png">
<meta property="og:updated_time" content="2020-09-25T00:53:28.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="前端性能及其优化">
<meta name="twitter:description" content="本文总结下前端性能及我们在开发过程中应该考虑到优化性能的部分">
<meta name="twitter:image" content="https://huangrenhao.gitee.io/2020/09/07/browser-performance-optimization/performance-timing.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://huangrenhao.gitee.io/2020/09/07/browser-performance-optimization/">





  <title>前端性能及其优化 | renhao</title>
  








<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">renhao</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://huangrenhao.gitee.io/2020/09/07/browser-performance-optimization/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="renhao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="renhao">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">前端性能及其优化</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-09-07T09:55:12+08:00">
                2020-09-07
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/browser/" itemprop="url" rel="index">
                    <span itemprop="name">browser</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/09/07/browser-performance-optimization/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2020/09/07/browser-performance-optimization/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  3
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文总结下前端性能及我们在开发过程中应该考虑到优化性能的部分<a id="more"></a></p>
<h3 id="性能参数"><a href="#性能参数" class="headerlink" title="性能参数"></a>性能参数</h3><p><code>window.performance.timing</code>接口获取当前页面中与性能相关的信息</p>
<p><img src="/2020/09/07/browser-performance-optimization/performance-timing.png" alt="performance.timing" style="zoom:48%;"></p>
<ul>
<li><p>浏览器交互阶段（Processing 和 onLoad）：浏览器接收到服务器返回的数据后，对 html 内容进行解析构建 dom 树，同时下载所需 css、js、媒体文件（视频、图片、声音）等</p>
</li>
<li><p>白屏时间：从浏览器响应用户输入网址到浏览器开始显示内容的时间。通常认为浏览器开始渲染 body 或者解析完 head 的时刻就是页面白屏的结束点。</p>
<p>计算方式：</p>
<ul>
<li>在 chrome 下可以通过 <code>window.chrome.loadTimes().firstPaintTime * 1000 - window.performance.timing.navigationStart</code></li>
<li>其他浏览器下可以通过 requestAnimationFrame 下获取渲染时间 <code>Date.now() - performance.timing.navigationStart</code>，将这个 script 脚本放入 head。利用 js 线程和渲染线程互斥</li>
</ul>
</li>
<li><p>首屏时间：从浏览器响应用户输入网址到首屏内容渲染完成的时间。</p>
<p>计算方式：</p>
<ul>
<li>如果没有图片等资源可以在特定的标签下打点计算结束时间</li>
<li>有图片资源：监听首屏高度内图片加载 onload 事件，最终遍历取最大值，用这个最大值减去 navigationStart 可获取近似的首屏时间</li>
</ul>
</li>
<li><p>dns 寻址时间：<code>domainLookupEnd - domainLookupStart</code></p>
</li>
<li><p>tcp 连接耗时：<code>connectEnd - connectStart</code></p>
</li>
<li><p>首包时间：<code>responseStart-navigationStart</code></p>
</li>
<li><p>request 请求耗时：<code>responseEnd - requestStart</code></p>
</li>
<li><p>解析 dom 树结构时间：<code>domComplete - domLoading</code></p>
</li>
</ul>
<h3 id="前端优化策略"><a href="#前端优化策略" class="headerlink" title="前端优化策略"></a>前端优化策略</h3><ul>
<li><p>优化渲染</p>
<ul>
<li>css 放到 head：css 有单独的下载线程异步下载，css 的加载不会影响 dom 树解析，但会阻塞 render 树渲染。</li>
<li>script 放到 底部或者加上 defer 或 async：浏览器渲染进程中 GUI 渲染线程与 js 引擎线程互斥，故当 HTML 解析到 script 标签时会暂停构建 dom，完成 js 下载并解析之后才会从暂停的地方重新开始。加了 defer 之后脚本文件下载与 html 解析并行执行，不过需要等待 html 解析完成之后再顺序执行。加了 async 之后脚本文件下载与 html 解析也是并行执行，但脚本下载完成之后暂停解析 html ，立即执行 js，async 不能确保执行的顺序。</li>
<li>预加载：尽早获取资源，不阻塞 onload。使用 <code>&lt;link rel=&#39;preload&#39;...</code></li>
<li>预渲染：下载后的文件预先在后台渲染，使用 <code>&lt;link rel=&#39;prerender&#39; ...</code></li>
<li>懒执行：将某些逻辑延迟到使用时再计算</li>
<li>懒加载：不关键资源延后加载，只加载自定义区域  </li>
</ul>
</li>
<li><p>减少请求数量（tcp 三次握手延时）</p>
<ul>
<li><p>小图片使用 base64 编码嵌入 css 中的 url 中</p>
</li>
<li><p>使用雪碧图</p>
</li>
<li><p>使用缓存：强缓存与协商缓存区别</p>
</li>
<li><p>使用持久连接：HTTP/1.0+“keep-alive”连接和 HTTP/1.1“persistent”连接，只有当连接上所有的报文都有正确的、自定义报文长度时（实体部分长度和 content-length 一致）连接才  能保持持久。</p>
<p>HTTP/1.0 keep-alive 连接的客户端可以通过包含 Connection:Keep-Alive 首部请求将连接保持在打开状态，如果服务器愿意为下一条请求将连接保持在打开状态就在响应中包含相同的首部，如果响应中没有 Connection:Keep-Alive 首部客户端就认为服务器不支持keep-alive并在发回响应报文之后关闭连接。</p>
<p>HTTP/1.1 持久连接在默认情况下是激活的</p>
</li>
<li><p>使用 http2</p>
</li>
</ul>
</li>
<li><p>减少请求时间</p>
<ul>
<li>dns 预解析、预读取：使浏览器主动进行域名解析，范围包括文档中的所有链接。使用<code>&lt;link rel=&#39;dns-prefetch&#39;...</code></li>
<li>静态资源使用 cdn，可以使用多个 cdn 域名（单个域名有链接限制），cdn 域名要和主站域名不同（否则会带 cookie ）</li>
</ul>
</li>
</ul>
<blockquote>
<p>参考资源</p>
<p><a href="https://www.zhihu.com/question/45553646" target="_blank" rel="noopener">知乎：前端 白屏时间如何获取</a></p>
<p><a href="https://www.cnblogs.com/zourong/p/5649841.html" target="_blank" rel="noopener">利用 performance 属性查看网页性能</a></p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/09/06/https-certificate/" rel="next" title="https 中的数字证书与中间人攻击">
                <i class="fa fa-chevron-left"></i> https 中的数字证书与中间人攻击
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/09/24/js-interview/" rel="prev" title="前端面试总结 js 部分">
                前端面试总结 js 部分 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">renhao</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">94</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#性能参数"><span class="nav-number">1.</span> <span class="nav-text">性能参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#前端优化策略"><span class="nav-number">2.</span> <span class="nav-text">前端优化策略</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">renhao</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">265.9k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '2P1xqUWiCoNm14MH4yhURlJi-gzGzoHsz',
        appKey: 'uJN0uagHIVgXtBO1OuLV9Ban',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
